package top.appx.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.UriComponentsBuilder;
import top.appx.entity.UserEntity;
import top.appx.service.UserService;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;

/**
 * Created by lhzxd on 2017/5/3.
 */
@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 查询所有用户
     * @return
     */
    @GetMapping
    public Object query(){
        List<UserEntity> userEntities = userService.query();
        if(userEntities.isEmpty()){
            return new ResponseEntity<List<UserEntity>>(HttpStatus.NO_CONTENT);
        }
        return new ResponseEntity<List<UserEntity>>(userEntities,HttpStatus.OK);
    }

    /**
     * 根据id查询用户
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Object queryById(@PathVariable("id") String id){
        UserEntity userEntity = userService.findById(id);
        if(userEntity==null){
            return new ResponseEntity<UserEntity>(HttpStatus.NO_CONTENT);
        }
        return new ResponseEntity<UserEntity>(userEntity,HttpStatus.OK);
    }

    /**
     *
     * 增加用户
     * @param userEntity
     * @param ucBuilder
     * @return
     */
    @PostMapping
    public Object addUser(@Valid UserEntity userEntity,UriComponentsBuilder ucBuilder){
        userService.addUser(userEntity);
        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(ucBuilder.path("/users/{id}").buildAndExpand(userEntity.getId()).toUri());
        return new ResponseEntity<UserEntity>(headers,HttpStatus.CREATED);
    }

    /**
     * 更新用户(需要提供用户的所有信息)
     * @param id
     * @param userEntity
     * @return
     */
    @PutMapping("/{id}")
    public Object updateUser(@PathVariable String id,@Valid UserEntity userEntity){
        userService.updateUser(userEntity);
        return new ResponseEntity<UserEntity>(userEntity,HttpStatus.OK);
    }


    /**
     *
     * 更新用户的部分属性
     * @param id
     * @param userEntity
     * @return
     */
    @PatchMapping("/{id}")
    public Object updateUserPatch(@PathVariable String id,@Valid UserEntity userEntity){
        userService.updateUserPatch(userEntity);
        return new ResponseEntity<UserEntity>(userEntity,HttpStatus.OK);
    }

    /**
     * 删除用户
     * @param id
     * @param response
     * @return
     */
    @DeleteMapping("/{id}")
    public Object del(@PathVariable("id") String id, HttpServletResponse response){
        userService.delUser(id);
        return new ResponseEntity<UserEntity>(HttpStatus.NO_CONTENT);
    }



}
